<template>
  <div class="app-main-content-box">
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="弹窗类型" prop="popType">
        <el-radio
          v-model="form.popType"
          :label="1"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check' ||
            pageRoter.pageType === 'edit' ||
            (pageRoter.pageType === 'add' && pageRoter.id)
              ? true
              : false
          "
          @change="toGeneralPop"
          >普通弹窗
        </el-radio>
        <el-radio
          v-model="form.popType"
          :label="2"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check' ||
            pageRoter.pageType === 'edit' ||
            (pageRoter.pageType === 'add' && pageRoter.id)
              ? true
              : false
          "
          @change="getPopStore"
          >储值弹窗</el-radio
        >
      </el-form-item>
      <!-- 标题 -->
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="form.title"
          type="text"
          maxlength="10"
          show-word-limit
          style="width: 30%"
          placeholder="请输入标题"
          :disabled="
            pageRoter.popState === 2 || pageRoter.pageType === 'check'
              ? true
              : false
          "
        />
      </el-form-item>

      <!-- 有效期 -->
      <div>
        <el-form-item
          v-if="pageRoter.popState === 2 && pageRoter.pageType === 'edit'"
          label="有效期"
          prop="validDate"
        >
          <el-date-picker
            v-model="form.startTime"
            align="center"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="开始日期"
            disabled
          />
          ~
          <el-date-picker
            v-model="form.endTime"
            align="center"
            type="datetime"
            placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item v-else label="有效期" prop="validDate">
          <el-date-picker
            v-model="form.validDate"
            align="center"
            :default-time="defaultTime"
            type="datetimerange"
            range-separator="~"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="pageRoter.pageType === 'check'"
            @change="timerangeFn"
          />
        </el-form-item>
      </div>

      <!-- 显示设置 -->
      <el-form-item label="显示设置" prop="showType">
        <el-radio-group
          v-model="form.showType"
          @change="showSetting"
          :disabled="
            pageRoter.popState === 2 || pageRoter.pageType === 'check'
              ? true
              : false
          "
        >
          <el-radio :label="1">
            <el-input
              v-model="form.showTimes"
              type="text"
              style="width: 100px; display: none"
              size="small"
              :disabled="
                pageRoter.popState === 2 || pageRoter.pageType === 'check'
                  ? true
                  : false
              "
            />
            每次进入店铺显示</el-radio
          >
          <el-radio :label="2">
            <el-input
              v-model="form.showRadio"
              type="text"
              style="width: 100px"
              size="small"
              :disabled="
                pageRoter.popState === 2 || pageRoter.pageType === 'check'
                  ? true
                  : false
              "
            />天显示一次
          </el-radio>
          <el-radio :label="3"> 规则星期每次进入店铺显示 </el-radio>
          <el-radio :label="4"> 规则星期显示一次 </el-radio>
        </el-radio-group>
      </el-form-item>

      <div v-if="form.showType === 1 || form.showType === 2">
        <div v-for="(ruleItem, ruleIndex) in form.ruleVos" :key="ruleIndex">
          <!-- 弹窗图 -->
          <el-form-item
            label="弹窗图"
            prop="ruleVos[0].imgUrl"
            :rules="rules.imgUrl"
            class="bigImg"
          >
            <div
              v-if="
                form.popType === 1 ||
                pageRoter.pageType === 'check' ||
                pageRoter.popState === 2
              "
              class="img-list"
            >
              <div class="img-item">
                <div v-if="isUpload" class="handle-icon">
                  <i
                    class="el-icon-zoom-in icon"
                    @click="handlePreview(ruleIndex)"
                  />
                  <i
                    v-if="
                      (pageRoter.pageType === 'edit' &&
                        pageRoter.popState !== 2) ||
                      pageRoter.pageType === 'add'
                    "
                    class="el-icon-delete icon"
                    @click="handleRemove(ruleIndex)"
                  />
                </div>
                <el-upload
                  class="app-uploader-img-plus fl"
                  :action="actionUrl"
                  :show-file-list="false"
                  :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                  :on-success="(res) => handleAvatarSuccess(res, ruleIndex)"
                  :before-upload="beforeAvatarUpload"
                  :on-remove="handleRemove"
                  :disabled="
                    pageRoter.popState === 2 || pageRoter.pageType === 'check'
                      ? true
                      : false
                  "
                >
                  <img
                    v-if="form.ruleVos[ruleIndex].imgUrl"
                    :src="fileBaseUrl + form.ruleVos[ruleIndex].imgUrl"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
                </el-upload>
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                style="width: 50%; margin-left: 50%"
              >
                <img style="width: 100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
              <ul class="upload_tips_img">
                <li>建议尺寸600*800px,大小1m内</li>
                <li>支持使用GIF格式</li>
              </ul>
            </div>
            <div
              v-if="
                form.popType === 2 &&
                (pageRoter.pageType === 'add' ||
                  (pageRoter.pageType === 'edit' && pageRoter.popState === 1))
              "
              class="img-list"
            >
              <div
                v-for="(item, index) in imgList"
                :key="index"
                class="img-item"
                :class="{ activeImg: curIndex === index }"
                @click="chooseImg(index, ruleIndex)"
              >
                <div class="handle-icon">
                  <i
                    class="el-icon-zoom-in icon"
                    @click="handlePreview(ruleIndex)"
                  />
                  <!-- <i
                class="el-icon-delete icon"
                @click="handleRemoveStore(index)"
              /> -->
                </div>
                <!-- <el-upload
                  class="app-uploader-img-plus fl"
                  :action="actionUrl"
                  :show-file-list="false"
                  :headers="uploadHeaders"
                  :on-success="(res) => handleAvatarSuccess(res, ruleIndex)"
                  :before-upload="beforeAvatarUpload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :disabled="
                    pageRoter.popState === 2 || pageRoter.pageType === 'check'
                      ? true
                      : false
                  "
                > -->
                <img
                  :src="fileBaseUrl + item"
                  class="avatar"
                  style="max-width: 180px"
                />
                <!-- </el-upload> -->
              </div>
            </div>
            <el-dialog
              title="图片预览"
              :visible.sync="dialogImageVisible"
              style="width: 50%; margin-left: 20%"
            >
              <img
                style="width: 100%"
                :src="fileBaseUrl + form.ruleVos[ruleIndex].imgUrl"
                alt
              />
            </el-dialog>
          </el-form-item>

          <!-- 站内链接 -->
          <el-form-item
            label="站内链接"
            :prop="form.popType === 1 ? 'path' : ''"
          >
            <div v-if="form.popType === 1">
              <el-button
                size="small"
                :disabled="
                  pageRoter.popState === 2 || pageRoter.pageType === 'check'
                    ? true
                    : false
                "
                @click="openInsideLink(ruleIndex)"
                >选择链接</el-button
              >
              <div v-if="form.ruleVos[ruleIndex].insideParams.remark">
                链接地址：{{ form.ruleVos[ruleIndex].insideParams.remark }}
              </div>
            </div>
            <div v-else-if="form.popType === 2">余额充值</div>
          </el-form-item>

          <!-- 是否悬浮 -->
          <el-form-item
            label="是否悬浮"
            prop="ruleVos[0].isOver"
            :rules="rules.isOver"
            class="suspend"
          >
            <el-radio
              v-model="form.ruleVos[ruleIndex].isOver"
              :label="true"
              :disabled="
                pageRoter.popState === 2 || pageRoter.pageType === 'check'
                  ? true
                  : false
              "
              @change="vaildFn"
              >是</el-radio
            >
            <el-radio
              v-model="form.ruleVos[ruleIndex].isOver"
              :label="false"
              :disabled="
                pageRoter.popState === 2 || pageRoter.pageType === 'check'
                  ? true
                  : false
              "
              @change="vaildFn"
              >否</el-radio
            >
          </el-form-item>

          <!-- 悬浮小图 -->
          <!-- 有开启悬浮需要上传图片，支持GIF图 -->
          <el-form-item
            :prop="
              form.ruleVos[ruleIndex].isOver === true
                ? 'ruleVos[0].overUrl'
                : ''
            "
          >
            <div v-if="form.ruleVos[ruleIndex].isOver === true">
              <el-upload
                class="app-uploader-img-plus uploader-small fl"
                :action="actionUrl"
                :show-file-list="false"
                :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                :on-success="(res) => handleAvatarSuccessSm(res, ruleIndex)"
                :before-upload="beforeAvatarUploadSuspend"
                :disabled="
                  pageRoter.popState === 2 || pageRoter.pageType === 'check'
                    ? true
                    : false
                "
              >
                <div>
                  <img
                    v-if="form.ruleVos[ruleIndex].overUrl"
                    :src="fileBaseUrl + form.ruleVos[ruleIndex].overUrl"
                    class="avatar-small"
                  />
                  <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
                </div>
              </el-upload>
              <ul class="upload_tips">
                <li>建议尺寸200*200px,大小1m内</li>
                <li>支持使用GIF格式</li>
                <li v-if="form.popType === 2" class="suspend-css">
                  <el-button
                    type="text"
                    :disabled="
                      form.ruleVos[ruleIndex].overUrl === overImgList[curIndex]
                        ? true
                        : false
                    "
                    @click="resume"
                    >恢复样式</el-button
                  >
                </li>
              </ul>
            </div>
            <div v-else />
          </el-form-item>
        </div>
      </div>

      <!-- 星期选择、 -->
      <div v-else class="week-rules">
        <div v-for="(ruleItem, ruleIndex) in form.ruleVos" :key="ruleIndex">
          <el-card style="width: 60%">
            <div class="flexRBC">
              <div>规则 {{ ruleIndex + 1 }}</div>
              <el-button
                type="text"
                v-if="form.ruleVos.length > 1"
                @click.prevent="delRules(ruleIndex)"
                >删除</el-button
              >
            </div>
            <!-- 有效星期 -->
            <el-form-item
              label="选择星期"
              :prop="'ruleVos.' + ruleIndex + '.availableWeeks'"
              :rules="rules.availableWeeks"
            >
              <el-checkbox-group
                v-model="ruleItem.availableWeeks"
                @change="selectWeek($event, ruleIndex)"
                :disabled="
                  pageRoter.popState === 2 || pageRoter.pageType === 'check'
                "
              >
                <el-checkbox-button
                  v-for="(weekItem, weekIndex) in weekOptions"
                  :key="'week-' + weekIndex"
                  :label="String(weekItem.value)"
                  :disabled="
                    !ruleItem.availableWeeks.includes('' + weekItem.value) &&
                    isSelectList.includes('' + weekItem.value)
                  "
                >
                  {{ weekItem.label }}
                </el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
            <!-- 弹窗图 -->
            <el-form-item
              label="弹窗图"
              :prop="'ruleVos.' + ruleIndex + '.imgUrl'"
              :rules="rules.imgUrl"
              class="bigImg"
            >
              <div
                v-if="
                  form.popType === 1 ||
                  pageRoter.pageType === 'check' ||
                  pageRoter.popState === 2
                "
                class="img-list"
              >
                <div class="img-item">
                  <div v-if="ruleItem.imgUrl" class="handle-icon">
                    <i
                      class="el-icon-zoom-in icon"
                      @click="handlePreview(ruleIndex)"
                    />
                    <i
                      v-if="
                        (pageRoter.pageType === 'edit' &&
                          pageRoter.popState !== 2) ||
                        pageRoter.pageType === 'add'
                      "
                      class="el-icon-delete icon"
                      @click="handleRemove(ruleIndex)"
                    />
                  </div>
                  <el-upload
                    class="app-uploader-img-plus fl"
                    :action="actionUrl"
                    :show-file-list="false"
                    :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                    :on-success="(res) => handleAvatarSuccess(res, ruleIndex)"
                    :before-upload="beforeAvatarUpload"
                    :on-remove="handleRemove"
                    :disabled="
                      pageRoter.popState === 2 || pageRoter.pageType === 'check'
                        ? true
                        : false
                    "
                  >
                    <img
                      v-if="ruleItem.imgUrl"
                      :src="fileBaseUrl + ruleItem.imgUrl"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
                  </el-upload>
                </div>
                <el-dialog
                  :visible.sync="dialogVisible"
                  style="width: 50%; margin-left: 50%"
                >
                  <img style="width: 100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
                <ul class="upload_tips_img">
                  <li>建议尺寸600*800px,大小1m内</li>
                  <li>支持使用GIF格式</li>
                </ul>
              </div>
              <div
                v-if="
                  form.popType === 2 &&
                  (pageRoter.pageType === 'add' ||
                    (pageRoter.pageType === 'edit' && pageRoter.popState === 1))
                "
                class="img-list"
              >
                <div
                  v-for="(item, index) in imgList"
                  :key="index"
                  class="img-item"
                  :class="{
                    activeImg: form.ruleVos[ruleIndex].selectIndex === index,
                  }"
                  @click="chooseImg(index, ruleIndex)"
                >
                  <div class="handle-icon">
                    <i
                      class="el-icon-zoom-in icon"
                      @click="handlePreviewStore(item)"
                    />
                    <!-- <i
                class="el-icon-delete icon"
                @click="handleRemoveStore(index)"
              /> -->
                  </div>
                  <!-- <el-upload
                    class="app-uploader-img-plus fl"
                    :action="actionUrl"
                    :show-file-list="false"
                    :headers="uploadHeaders"
                    :on-success="(res) => handleAvatarSuccess(res, ruleIndex)"
                    :before-upload="beforeAvatarUpload"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :disabled="
                      pageRoter.popState === 2 || pageRoter.pageType === 'check'
                        ? true
                        : false
                    "
                  > -->
                  <img
                    :src="fileBaseUrl + item"
                    class="avatar"
                    style="max-width: 180px"
                  />
                  <!-- </el-upload> -->
                </div>
              </div>
              <el-dialog
                title="图片预览"
                :visible.sync="dialogImageVisible"
                style="width: 50%; margin-left: 20%"
              >
                <img
                  style="width: 100%"
                  :src="fileBaseUrl + dialogImageUrl"
                  alt
                />
              </el-dialog>
            </el-form-item>

            <!-- 站内链接 -->
            <el-form-item label="站内链接">
              <div v-if="form.popType === 1">
                <el-button
                  size="small"
                  :disabled="
                    pageRoter.popState === 2 || pageRoter.pageType === 'check'
                      ? true
                      : false
                  "
                  @click="openInsideLink(ruleIndex)"
                  >选择链接</el-button
                >
                <div v-if="form.ruleVos[ruleIndex].insideParams.remark">
                  链接地址：{{ form.ruleVos[ruleIndex].insideParams.remark }}
                </div>
              </div>
              <div v-else-if="form.popType === 2">余额充值</div>
            </el-form-item>

            <!-- 是否悬浮 -->
            <el-form-item
              label="是否悬浮"
              :prop="'ruleVos.' + ruleIndex + '.isOver'"
              :rules="rules.isOver"
              class="suspend"
            >
              <el-radio
                v-model="ruleItem.isOver"
                :label="true"
                :disabled="
                  pageRoter.popState === 2 || pageRoter.pageType === 'check'
                    ? true
                    : false
                "
                @change="vaildFn"
                >是</el-radio
              >
              <el-radio
                v-model="ruleItem.isOver"
                :label="false"
                :disabled="
                  pageRoter.popState === 2 || pageRoter.pageType === 'check'
                    ? true
                    : false
                "
                @change="vaildFn"
                >否</el-radio
              >
            </el-form-item>

            <!-- 悬浮小图 -->
            <!-- 有开启悬浮需要上传图片，支持GIF图 -->
            <el-form-item
              :prop="
                ruleItem.isOver === true
                  ? 'ruleVos.' + ruleIndex + '.overUrl'
                  : 'over'
              "
            >
              <div v-if="ruleItem.isOver === true">
                <el-upload
                  class="app-uploader-img-plus uploader-small fl"
                  :action="actionUrl"
                  :show-file-list="false"
                  :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                  :on-success="(res) => handleAvatarSuccessSm(res, ruleIndex)"
                  :before-upload="beforeAvatarUploadSuspend"
                  :disabled="
                    pageRoter.popState === 2 || pageRoter.pageType === 'check'
                      ? true
                      : false
                  "
                >
                  <div>
                    <img
                      v-if="ruleItem.overUrl"
                      :src="fileBaseUrl + ruleItem.overUrl"
                      class="avatar-small"
                    />
                    <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
                  </div>
                </el-upload>
                <ul class="upload_tips">
                  <li>建议尺寸200*200px,大小1m内</li>
                  <li>支持使用GIF格式</li>
                  <li v-if="form.popType === 2" class="suspend-css">
                    <el-button
                      type="text"
                      :disabled="
                        ruleItem.overUrl === overImgList[curIndex]
                          ? true
                          : false
                      "
                      @click="resume"
                      >恢复样式</el-button
                    >
                  </li>
                </ul>
              </div>
              <div v-else />
            </el-form-item>
          </el-card>
        </div>
        <el-button
          type="text"
          icon="el-icon-plus"
          @click.native.prevent="addRules"
          v-if="form.ruleVos.length < 7"
          :disabled="pageRoter.popState === 2 || pageRoter.pageType === 'check'"
          >增加规则</el-button
        >
      </div>

      <el-form-item>
        <el-button :disabled="false" @click="cancelFn">取消</el-button>
        <el-button
          v-if="pageRoter.pageType === 'add' || pageRoter.pageType === 'edit'"
          type="primary"
          :disabled="false"
          @click="savePop"
          >保存</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 站内链接弹窗 -->
    <DialogInsideLink ref="insideLink" />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import DialogInsideLink from "@/views/wxaBuildModule/views/components/DialogInsideLink";
import { imgUploadUrl } from "@/api/upload";
import {
  PopConfigListAdd,
  PopConfigPicList,
  getPopById,
  PopConfigListUpdate,
} from "@/api/marketing";
export default {
  components: {
    DialogInsideLink,
  },
  data() {
    const disabledDate = (date) => {
      return date.getTime() < new Date().getTime() - 86400000;
    };
    return {
      loading: false,
      pageRoter: this.$route.query,
      isUpload: false,
      isShowRemove: true,
      actionUrl: imgUploadUrl, // 图片下载路径
      dialogImageVisible: false,
      dialogVisible: false,
      dialogImageUrl: "",
      uploadHeaders: {},
      pickerOptions: {
        // 筛选日期
        disabledDate,
        // selectableRange 用来限制时分秒的选择，这里要求只能选择当前时间之后到0点的时间点 但应该只限今天
        // selectableRange: '00:00:00 - 23:59:59'
      },
      imgList: [], // 弹窗图列表
      overImgList: [], // 悬浮图
      curIndex: 0, // 默认选中第一张图
      defaultTime: [],
      time: "",
      isSelectList: [],
      isSelect: false,
      checkItem: "",
      weekOptions: [
        { label: "周一", value: 2 },
        { label: "周二", value: 3 },
        { label: "周三", value: 4 },
        { label: "周四", value: 5 },
        { label: "周五", value: 6 },
        { label: "周六", value: 7 },
        { label: "周日", value: 1 },
      ],
      // 表单
      form: {
        id: null,
        popType: 1,
        title: "",
        validDate: [
          this.$momentMini().format("YYYY-MM-DD"),
          this.$momentMini().format("YYYY-MM-DD"),
        ],
        startTime: "",
        endTime: "",
        showRule: null,
        showRadio: null,
        showType: 1,
        showTimes: null,
        ruleVos: [
          {
            ruleVosIndex: null,
            selectIndex: 0,
            id: null,
            imgUrl: "",
            isOver: true,
            overUrl: "",
            appId: "",
            feature: "",
            featureParams: "",
            insidePage: "",
            insideParams: "",
            path: "",
            type: "INSIDE",
            url: "",
            weeks: "",
            availableWeeks: [],
          },
        ],
      },
      // 表单校验
      rules: {
        popType: [
          {
            required: true,
            message: "请选择弹窗的类型",
            trigger: ["blur", "change"],
          },
        ],
        title: [
          {
            required: true,
            message: "请填写标题",
            trigger: ["blur", "change"],
          },
          {
            min: 1,
            max: 10,
            message: "请输入1到10位之间",
            trigger: ["blur", "change"],
          },
        ],
        validDate: [
          {
            required: true,
            message: "请选择弹窗的有效日期",
            trigger: ["change"],
          },
        ],
        isOver: [
          {
            required: true,
            message: "请选择是否悬浮",
            trigger: ["change"],
          },
        ],
        imgUrl: [
          {
            required: true,
            message: "请选择弹窗图",
            trigger: ["blur", "change"],
          },
        ],
        showType: [
          {
            required: true,
            message: "请选择显示设置",
            trigger: ["blur", "change"],
          },
        ],
        overUrl: [
          {
            required: true,
            message: "请选择弹窗图",
            trigger: ["blur", "change"],
          },
        ],
        over: [
          {
            message: "请选择弹窗图",
            trigger: ["blur", "change"],
          },
        ],
        availableWeeks: [
          {
            required: true,
            message: "请选择星期",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },

  computed: {
    ...mapGetters(["fileBaseUrl"]),
  },

  created() {
    this.getTimeFun();
  },

  mounted() {
    this.getPopStore();
    this.fetchData();
  },

  methods: {
    // 获取当前时间
    getTimeFun() {
      const yy = new Date().getFullYear();
      const mm = new Date().getMonth() + 1;
      const dd = new Date().getDate();
      const hh = new Date().getHours();
      const mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      const ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      this.time = hh + ":" + mf + ":" + ss;
      this.defaultTime = [this.time, "23:59:59"];
    },

    // 站内链接
    openInsideLink(index) {
      this.$refs.insideLink.open({ row: this.form }).then((res) => {
        this.form.ruleVos[index].insidePage = res.insidePage || null;
        this.form.ruleVos[index].insideParams = {
          insidePageType: res.insideParams.insidePageType || null,
          pageId: (res.insideParams && res.insideParams.pageId) || null,
          goodsSerial:
            (res.insideParams && res.insideParams.goodsSerial) || null,
          commonCode: (res.insideParams && res.insideParams.commonCode) || null,
          remark: (res.insideParams && res.insideParams.remark) || null,
        };
        this.form.ruleVos[index].mode = res.mode || null;
        this.form.ruleVos[index].path = res.path || null;
      });
    },

    handleAvatarSuccess(res, index) {
      if (res.code === 0) {
        this.isUpload = true;
        this.form.ruleVos[index].imgUrl = res.data.path;

        this.$refs.form.clearValidate(["imgUrl"]);
      } else {
        this.$message.error(res.msg);
      }
    },
    handleAvatarSuccessSm(res, index) {
      if (res.code === 0) {
        this.form.ruleVos[index].overUrl = res.data.path;
        this.$refs.form.clearValidate(["overUrl"]);
      } else {
        this.$message.error(res.msg);
      }
    },
    // 上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1, ["JPG", "PNG", "GIF"]);
    },
    beforeAvatarUploadSuspend(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1, ["JPG", "PNG", "GIF"]);
    },
    // 删除图片
    handleRemove(index) {
      this.form.ruleVos[index].imgUrl = "";
      this.isUpload = false;
    },

    // 图片放大
    handlePreview(index) {
      this.dialogImageUrl = this.form.ruleVos[index].imgUrl;
      this.dialogImageVisible = true;
    },

    handlePreviewStore(path) {
      this.dialogImageUrl = path;
      this.dialogImageVisible = true;
    },

    // 有效时间限制
    timerangeFn(val) {
      this.form.startTime = val[0];
      this.form.endTime = val[1];
      const startTime = new Date(val[0]);
      const curTime = new Date();
      // if (this.pageRoter.pageType === 'add') {
      //   if (startTime.getTime() <= curTime.getTime()) {
      //     this.$message.warning('有效期不可选择已过时间')
      //     this.form.validDate = ''
      //     return
      //   }
      // } else {
      return this.form.validDate;
      // }
    },

    // 恢复样式
    resume() {
      for (let i = 0; i < this.form.ruleVos.length; i++) {
        this.form.ruleVos[i].overUrl = this.overImgList[this.curIndex];
      }
    },

    // 获取弹窗图列表
    async getPopStore() {
      const res = await PopConfigPicList();
      this.imgList = res.data.backgroundUrl;
      this.overImgList = res.data.overImgUrl;
      this.curIndex = this.imgList.findIndex((item) => {
        for (let i = 0; i < this.form.ruleVos.length; i++) {
          return item === this.form.ruleVos[i].imgUrl;
        }
      });
    },

    // 清空储值弹窗的图片联动
    async toGeneralPop() {
      this.form.ruleVos.forEach((item) => {
        item.imgUrl = "";
        item.overUrl = "";
      });
      this.form.title = "";
      this.form.validDate = [];
      await this.$refs.form.clearValidate();
    },

    // 切换单选时清空校验
    vaildFn() {
      this.$refs.form.clearValidate();
    },

    //  选中的大图片
    chooseImg(index, i) {
      this.curIndex = index;
      this.form.ruleVos[i].ruleVosIndex = i;
      this.form.ruleVos[i].selectIndex = index;
      this.form.ruleVos[i].imgUrl = this.imgList[index];
      this.form.ruleVos[i].overUrl = this.overImgList[index];
    },

    // 编辑查看复制数据回填
    async fetchData() {
      this.form.id = this.pageRoter.id;
      if (
        this.pageRoter.pageType === "edit" ||
        this.pageRoter.pageType === "check" ||
        (this.pageRoter.pageType === "add" && this.pageRoter.id)
      ) {
        this.isUpload = true;
        const res = await getPopById(this.form.id);
        this.form = res.data;

        for (let i = 0; i < this.form.ruleVos.length; i++) {
          this.form.ruleVos[i].insideParams = JSON.parse(
            this.form.ruleVos[i].insideParams
          );
          this.form.ruleVos[i].availableWeeks =
            this.form.ruleVos[i].weeks.split(",");
          if (res.data.popType === 2) {
            // this.getPopStore()
            res.data.ruleVos.forEach((ruleItem) => {
              ruleItem.selectIndex = this.imgList.findIndex(
                (item) => item === ruleItem.imgUrl
              );
            });

            this.form.ruleVos[i].imgUrl = res.data.ruleVos[i].imgUrl;
            this.form.ruleVos[i].overUrl = res.data.ruleVos[i].overUrl;
          }
        }

        if (this.pageRoter.pageType === "add" && this.pageRoter.id) {
          this.form.id = null;
          // this.form.validDate = []
          this.form.startTime = "";
          this.form.endTime = "";
        }
        if (res.data.showType === 1) {
          if (res.data.showRule === 0) {
            this.form.showTimes = null;
          } else {
            this.form.showRadio = null;
          }
        } else if (res.data.showType === 2) {
          this.form.showRadio = Number(res.data.showRule);
        }
        const dateList = [res.data.startTime, res.data.endTime];
        this.$set(this.form, "validDate", dateList);
      }
    },

    // 弹窗新增编辑查看
    async savePop() {
      const data = JSON.parse(JSON.stringify(this.form));
      if (this.form.showType === 1) {
        data.showRule = 0;
      } else if (this.form.showType === 2) {
        data.showRule = Number(this.form.showRadio);
      } else if (this.form.showType === 3) {
        data.showRule = -1;
      } else if (this.form.showType === 4) {
        data.showRule = -2;
      }
      await this.$refs.form.validate();
      this.loading = true;
      // 发情求
      if (
        this.pageRoter.pageType === "add" ||
        (this.pageRoter.pageType === "add" && this.pageRoter.id)
      ) {
        // 普通弹窗
        if (this.form.popType === 1) {
          for (let i = 0; i < data.ruleVos.length; i++) {
            data.ruleVos[i].insideParams = JSON.stringify(
              this.form.ruleVos[i].insideParams
            );
            data.ruleVos[i].weeks = data.ruleVos[i].availableWeeks.length ? data.ruleVos[i].availableWeeks.join(",") : ''

            if (this.form.ruleVos[i].availableWeeks === []) {
              this.form.ruleVos.splice(i, 1);
            }

          }
          const res = await PopConfigListAdd(data);
          if (res.code === 0) {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000,
              offset: 40,
            });
            this.loading = false;
            this.$router.push({ name: "MarketingActivityDialog" });
          } else {
            this.loading = false;
            this.$message.error(res.msg);
          }
        } else {
          for (let i = 0; i < data.ruleVos.length; i++) {
            const insideParams = {
              remark: "余额充值",
              goodsSerial: null,
            };
            data.ruleVos[i].insideParams = JSON.stringify(insideParams);
            data.ruleVos[i].path =
              "/pages/memberCardModule/pages/balanceRecharge/main";
              console.log(1111, data.ruleVos[i].availableWeeks)
            data.ruleVos[i].weeks = data.ruleVos[i].availableWeeks.join(",");
          }
          const res = await PopConfigListAdd(data);
          if (res.code === 0) {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000,
              offset: 40,
            });
            this.loading = false;
            this.$router.push({ name: "MarketingActivityDialog" });
          } else {
            this.loading = false;
            this.$message.error(res.msg);
          }
        }
      } else if (this.pageRoter.pageType === "edit") {
        for (let i = 0; i < data.ruleVos.length; i++) {
          data.ruleVos[i].insideParams = JSON.stringify(
            data.ruleVos[i].insideParams
          );
          if (this.form.showType == 3 || 4) {
            data.ruleVos[i].weeks = data.ruleVos[i].availableWeeks.join(",");
          }
          if (this.form.popType === 2) {
            const insideParams = {
              remark: "余额充值",
              goodsSerial: null,
            };
            data.ruleVos[i].insideParams = JSON.stringify(insideParams);
            data.ruleVos[i].path =
              "/pages/memberCardModule/pages/balanceRecharge/main";
            data.ruleVos[i].weeks = data.ruleVos[i].availableWeeks.join(",");
          }
        }
        const res = await PopConfigListUpdate(data);
        if (res.code === 0) {
          this.$notify({
            title: "成功",
            message: "编辑成功",
            type: "success",
            duration: 2000,
            offset: 40,
          });

          this.loading = false;
          this.$router.push({ name: "MarketingActivityDialog" });
        } else {
          this.loading = false;
          this.$message.error(res.msg);
        }
      }
    },

    // 取消
    cancelFn() {
      this.$router.push({ name: "MarketingActivityDialog" });
    },

    // 增加规则
    addRules() {
      let newRules = {
        imgUrl: "",
        isOver: true,
        overUrl: "",
        appId: "",
        feature: "",
        featureParams: "",
        insidePage: "",
        insideParams: "",
        path: "",
        type: "INSIDE",
        url: "",
        weeks: "",
        availableWeeks: [],
      };
      this.form.ruleVos.push(newRules);
      this.form.ruleVos.map(item => this.isSelectList = [...this.isSelectList, ...item.availableWeeks])
      this.isUpload = false;
    },

    //  删除规则
    delRules(index) {
      this.form.ruleVos.splice(index, 1);
      const { ruleVos } = this.form
      let isSelectList = []
      ruleVos.map(item => {
        isSelectList = [...isSelectList, ...item.availableWeeks]
      })
      this.isSelectList = isSelectList
    },

    // 选择星期
    selectWeek(val, index) {
      this.$forceUpdate(); //由于数据层次太深，函数无法自动更新，需手动强制刷新
      this.form.ruleVos[index].weeks = val.join(",");
      let isSelectList = []; //接收选中的数组
      // 获取选中的数组
      this.form.ruleVos.forEach((selectItem) => {
        isSelectList.push(...selectItem.availableWeeks);
      });

      this.isSelectList = isSelectList; //选中的数组
      console.log(isSelectList)
    },

    showSetting(val) {
      this.form.ruleVos.splice(1);
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.suspend {
  margin-bottom: 0;
}
.el-button {
  padding: 12px 50px;
}

.week-rules {
  margin-bottom: 20px;
  .el-card {
    margin-left: 50px;
    margin-bottom: 10px;
  }
}

.app-uploader-img-plus ::v-deep {
  margin-right: 20px;
  width: 180px;
  height: 180px;
  .el-upload--picture-card {
    width: 180px;
    height: 180px;
    border: none;
  }

  .app-uploader-img-plus-icon {
    font-size: 36px;
    color: #8c939d;
    width: 180px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .avatar {
    width: 180px;
    height: 180px;
    display: block;
  }
}

// 小图
.uploader-small {
  margin-right: 20px;
  width: 100px;
  height: 100px;
  .app-uploader-img-plus-icon {
    font-size: 26px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar-small {
    width: 98px;
    height: 98px;
    display: block;
  }
}

.upload_tips {
  margin: 20px 0 0 20px;
  li {
    margin-top: 10px;
    font-size: 14px;
    line-height: 16px;
    color: $dark-font-color;
    .el-button {
      padding: 0;
    }
  }
}

.bigImg {
  .img-list {
    position: relative;
    margin: 0;
    vertical-align: top;
    cursor: pointer;
    .upload_tips_img {
      position: absolute;
      top: 14px;
      left: 190px;
      margin: 20px 0 0 20px;
      li {
        margin-top: 10px;
        font-size: 14px;
        line-height: 16px;
        color: $dark-font-color;
      }
    }
    .activeImg {
      width: 184px !important;
      height: 184px !important;
      border: 4px solid #ffb72f !important;
    }
    .img-item {
      position: relative;
      overflow: hidden;
      background-color: #fff;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      height: 180px;
      width: 180px;
      margin: 0 8px 8px 0;
      display: inline-block;
      border: none;
      .handle-icon {
        display: none;
      }
      &:hover {
        font-size: 20px;
        color: #fff;
        .handle-icon {
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);

          z-index: 999;
          .icon {
            margin: 10px;
          }
        }
      }
    }
  }
}

/deep/.el-checkbox-button.is-disabled.is-checked .el-checkbox-button__inner {
  color: #ffffff;
  background-color: $barActiveBgc;
  border-color: $barActiveBgc;
  -webkit-box-shadow: -1px 0 0 0 $barActiveBgc;
  box-shadow: -1px 0 0 0 $barActiveBgc;
}
</style>
